<?php
class SRDO_Database {
	public $database	= '';
	public $pdo			= null;
	
	/**
	 *
	 */
	public function __construct($database, PDO $pdo) {
		$this->database = $database;
		$this->pdo		= $pdo;
		
		if ( !isset(SRDO::$config['config']['default_db']) ) {
			SRDO::$config['config']['default_db'] = $this->database;
		}

		if ( !isset(SRDO::$config['database'][$this->database]) ) {
			SRDO::$config['database'][$this->database] = array(	'database'	=> $this->database,
																'pdo'		=> $this->pdo 
																);
		}
	}

	/**
	 * Returns a DB object (_connect already called!) or false
	 */
	public static function &getPDO($database = null) {
		if ( $database === null ) {
			$database = SRDO::$config['config']['default_db'];
		}

		if ( isset(SRDO::$config['database'][$database]['pdo']) &&
			is_object(SRDO::$config['database'][$database]['pdo']) ) {
			return SRDO::$config['database'][$database]['pdo'];
		}

		if ( !isset(SRDO::$config['database'][$database]['pdo']) ) {
			SRDO::error('&getDB(' . $database . '): PDO Connection object not found');
			return false;
		}
		SRDO::error('&getDB(' . $database . '): Database config not set');
		return false;
	}

	/**
	 * Alias doesn't do anything right now...
	 */
	public function &T($table, $alias = null) {
		if ( is_object($table) ) {
			$table = $table->table;
		}

		// Create our SRDO_Table object
		$oT = &new SRDO_Table($table, $alias, $this->database);
		SRDO::$config['database'][$this->database]['table'][$table] = $table;
		return $oT;
	}

	
	public function set($key, $value) {
		SRDO::$config['database'][$this->database]['var'][$key] = $value;
	}

	public static function getTable($db, $table) {
		if (!isset(SRDO::$config['database'][$db]['table'][$table])) {
			return false;
		}

		return SRDO_Table::getTable(SRDO::$config['database'][$db]['table'][$table]);
	}

	public static function getTableFields($db, $table) {
		if (!isset(SRDO::$config['database'][$db]['table'][$table])) {
			SRDO::error("getTableFields($db, $table): Returning false");
			return false;
		}

		return SRDO_Table::getFields(SRDO::$config['database'][$db]['table'][$table]);
	}

	public static function getTableKeys($db, $table) {
		if (!isset(SRDO::$config['database'][$db]['table'][$table])) {
			return false;
		}

		return SRDO_Table::getKeys(SRDO::$config['database'][$db]['table'][$table]);
	}

	public static function getTableVars($db, $table) {
		if (!isset(SRDO::$config['database'][$db]['table'][$table])) {
			return false;
		}

		return SRDO_Table::getVars(SRDO::$config['database'][$db]['table'][$table]);
	}


	/**
	 */
	public function validate($database = null) {
		if (!$database && !$this) {
			return false;
		} elseif (!$database) {
			$database = $this->database;
		}
		
		if (!isset(SRDO::$config['database'][$database])) {
			return false;
		}

		$ret = true;
		foreach (SRDO::$config['database'][$database]['table'] AS $k => $v) {
			if (!SRDO_Table::validate($v)) {
				$ret = false;
			}
		}

		return $ret;
	}
}